import axios from "axios";
import { siteTitle } from "@/settings";
import { getStorage, removeStorage } from "@/utils/common";
import {
  allowMultipleToast,
  showLoadingToast,
  closeToast,
  showFailToast,
} from "vant";
import router from "../router";
const request = axios.create({
  timeout: 60000,
});
// 允许出现多个Toast
allowMultipleToast();
// 请求拦截器
request.interceptors.request.use(
  (config) => {
    console.log(config);
    showLoadingToast({
      message: "加载中...",
      forbidClick: true,
      duration: 0,
    });
    const token = getStorage(`${siteTitle}_token`);
    config.headers["Content-Type"] = "application/json";
    config.headers["Authorization"] = token;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 请求返回拦截器
request.interceptors.response.use(
  (response) => {
    const res = response.data;
    const { code } = res;
    if (code === "SUCCESS") {
      // 清除loading toast
      closeToast();
      return Promise.resolve(res);
    } else if (code == 50008) {
      removeStorage(`${siteTitle}_token`);
      router.push("/home");
    }

    closeToast();
    if (res.code == 50008) {
      showFailToast("登录失效");
    } else {
      showFailToast(res.msg);
    }
    return Promise.reject(res);
  },
  (error) => {
    const errorText = error.response.data.msg;
    console.log(error);
    closeToast();
    showFailToast(errorText);
    return error;
  }
);

export default request;
